package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口获取openid
        String openid = getOpenid(userLoginDTO);

        //判断openid是否为空
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断用户是否为新用户，如果是新用户则完成注册功能
        User user = userMapper.selectByOpenid(openid);
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }


    private String getOpenid(UserLoginDTO userLoginDTO) {
        //调用微信接口获取openid
        HashMap param = new HashMap<>();
        param.put("appid","wxcecbd152f99b72b0");
        param.put("secret", "ae7c7de6a34958d624fbe54b49e61b82");
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code");
        String doGet = HttpClientUtil.doGet(WX_LOGIN, param);
        JSONObject json = JSON.parseObject(doGet);
        String openid = json.getString("openid");
        return openid;
    }
}
